package qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * qiniu
 *
 * @description:
 * @author: yechen
 * @email: wangqingfeng@wxyundian.com
 * @date: 2020年09月30日 16:09
 */
public class FileUtil {
    //静态方法中要用到的
    private static String FILE_SAVEPATH = "/data/upload";
    private static String FILE_URL_PREFIX = "https://api.hz139.com/upload/";
    private static String FILE_QINIU_DOMAIN = "http://qiniu.hz139.com";
    private static String FILE_QINIU_DOMAINHTTPS = "https://file.hz139.com";
    private static String FILE_DOWNLOAD_URL_PREFIX ="https://api.hz139.com/portal/image/download?imgurl=";

    /**
     * 将inputstream数据流上传到七牛服务器
     */
    public static String uploadIuputStream2Qiniu(InputStream inputStream, String filename) {
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "BRRrAo2Xr3FwYgsTw92a6n2mCz6gcKKjaOYXh-WR";
        String secretKey = "dUMxeZQAeURfQg1anRg1che2GhqMRaHCRXgGdewS";
        String bucket = "task";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(inputStream, filename, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            if(!StringUtils.isEmpty(putRet.key)){
                filename = putRet.key;
            }

        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return filename;
    }

    /**
     * 公有空间返回文件URL
     * @param fileName
     * @return
     */
    public static String getQiniuUrl(String fileName) {
//        String domainOfBucket = CustomizedPropertyConfigurer.getProperty("file.qiniu.domain");
        String encodedFileName=null;
        try {
            encodedFileName = URLEncoder.encode(fileName, "utf-8");
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }
        String finalUrl = String.format("%s/%s", FILE_QINIU_DOMAIN,encodedFileName );
        return finalUrl;
    }


    /**
     * 将用户上传的文件保存在服务器本地磁盘
     * @param inputStream
     * @param path
     * @return
     * @throws IOException
     */
    public static String saveFile(InputStream inputStream, String path) throws IOException {
        String url = null;
        Path targetPath = Paths.get(FILE_SAVEPATH, path);
        Path parent = targetPath.getParent();
        if (!Files.exists(parent)) {
            Files.createDirectories(parent);
        }
        Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);


        url = FILE_URL_PREFIX + path;
        return url;
    }


    public static String getExtension(String filename){
        String ext = FilenameUtils.getExtension(filename);
        if(ext == null){
            ext = "";
        }else{
            ext ="."+ext;
        }
        return ext;
    }
    public static String getLocalFilepath(String ext) {
        if(ext == null)
            ext="";
        return new SimpleDateFormat("yyyyMM/dd/").format(new Date()).concat(uuid() + ext);
    }

    public static String uuid(){
        return UUID.randomUUID().toString().replace("-","");
    }

    public static String getHTTPSDownloadUrl(String imgurl){
//        String httpsUrlPrefix = CustomizedPropertyConfigurer.getProperty("file.qiniu.domain.https");
//        String httpUrlPrefix = CustomizedPropertyConfigurer.getProperty("file.qiniu.domain");
        return imgurl.replace(FILE_QINIU_DOMAIN, FILE_QINIU_DOMAINHTTPS);
    }


//    @RequestMapping(value = "/upload", method = RequestMethod.POST)
//    @ResponseBody
//    public Response upload(@RequestParam("file") MultipartFile file){
//        if (null == file || file.isEmpty()) {
//            logger.error("上传的文件有误");
//            return Response.wrapError("上传的文件有误");
//        }
//        String contentType = file.getContentType();
//        //判断类型
//        for (String exclude : excludes) {
//            if (exclude.matches(contentType)) {
//                logger.error("不允许上传的文件类型");
//                return Response.wrapError("不允许上传的文件类型");
//            }
//        }
//        Map<String,String> uploadMap = new HashMap<>();
//        String fileUrl;
//
//        String filepath = FileUtil.uuid()  + FileUtil.getExtension(file.getOriginalFilename());
//        String targetFilepath;
//        try {
//            targetFilepath = FileUtil.uploadIuputStream2Qiniu(file.getInputStream(), filepath);
//        } catch (IOException e) {
//            return Response.wrapError("网络异常，请稍后再试");
//        }
//        fileUrl = FileUtil.getQiniuUrl(targetFilepath);
//        uploadMap.put("fileUrl", fileUrl);
//        return Response.wrapSuccess(uploadMap,"上传成功");
//    }
}
